package goods

import (
	"goods-rpc/models"
	good "goods-rpc/proto/goods"
)

func goodModelInfo(goodlist *models.Goods) (info *good.GoodsInfo, err error) {
	return &good.GoodsInfo{
		Id:          int64(goodlist.ID),
		GoodsName:   goodlist.GoodsName,
		GoodsStats:  goodlist.GoodsStats,
		GoodsUrl:    goodlist.GoodsUrl,
		GoodsShop:   goodlist.GoodsShop,
		GoodsNum:    int64(goodlist.GoodsNum),
		GoodsPrice:  float32(goodlist.GoodsPrice),
		CouponPrice: float32(goodlist.CouponPrice),
		CountPrice:  float32(goodlist.CountPrice),
		Preheating:  int64(goodlist.Preheating),
		GoodsStatus: int64(goodlist.GoodsStatus),
	}, nil
}

func goodModelList(goodlist []models.Goods) (info []*good.GoodsInfo, err error) {
	for _, v := range goodlist {
		info = append(info, &good.GoodsInfo{
			Id:          int64(v.ID),
			GoodsName:   v.GoodsName,
			GoodsStats:  v.GoodsStats,
			GoodsUrl:    v.GoodsUrl,
			GoodsShop:   v.GoodsShop,
			GoodsNum:    int64(v.GoodsNum),
			GoodsPrice:  float32(v.GoodsPrice),
			CouponPrice: float32(v.CouponPrice),
			CountPrice:  float32(v.CountPrice),
			Preheating:  int64(v.Preheating),
			GoodsStatus: int64(v.GoodsStatus),
			GoodsSort:   int64(v.GoodsSort),
		})
	}

	return info, nil
}

func TakeUpdateBYNum(id, GoodsNum int) (*good.GoodsInfo, error) {
	m := new(models.Goods)
	num, err := m.UpdateByNum(id, GoodsNum)
	if err != nil {
		return nil, err
	}
	return goodModelInfo(num)
}

func TakePreheating() ([]*good.GoodsInfo, error) {
	m := new(models.Goods)
	bySort, err := m.FindByPreheating()
	if err != nil {
		return nil, err
	}
	return goodModelList(bySort)
}

func TakeFindSort(sort int) ([]*good.GoodsInfo, error) {
	m := new(models.Goods)
	bySort, err := m.FindBySort(sort)
	if err != nil {
		return nil, err
	}
	return goodModelList(bySort)
}

func TakeFind(id int) (*good.GoodsInfo, error) {
	m := new(models.Goods)
	find, err := m.FindByID(id)
	if err != nil {
		return nil, err
	}

	return goodModelInfo(find)
}

func TakeList() ([]*good.GoodsInfo, error) {
	m := new(models.Goods)
	list, err := m.List()
	if err != nil {
		return nil, err
	}
	return goodModelList(list)
}

func TakeAdd(add models.Goods) (*good.GoodsInfo, error) {
	m := new(models.Goods)
	goods, err := m.Add(add)
	if err != nil {
		return nil, err
	}
	return goodModelInfo(goods)
}

func TakeDel(id int) (*good.GoodsInfo, error) {
	m := new(models.Goods)
	goodsdel, err := m.Del(id)
	if err != nil {
		return nil, nil
	}
	return goodModelInfo(goodsdel)
}
